// 字典类
#pragma once

#include <iostream>
#include <unordered_map>
#include <fstream>
#include <string>

using namespace std;


const string fpath = "./Dict.txt";
const string sep = ": ";

class Dict
{
private:
    bool Load()
    {
        ifstream in(filepath);
        // 打开文件失败
        if (!in.is_open())
        {
            cerr << "无法打开文件" << endl;
            return false;
        }
        // 从文件中读取数据
        string line;
        while(getline(in, line))
        {
            // 提取单词（work）和汉字（han）
            if(line.empty()) continue;
            auto pos = line.find(sep); 
            if(pos == string::npos) continue;
            string word = line.substr(0, pos);
            if(word.empty()) continue;
            string han = line.substr(pos+sep.size());
            if(han.empty()) continue;

            cout << word << ": " << han << endl;
            // 将从文件中提取到的数据插入字典中
            _dict.insert(make_pair(word, han));
        }
        in.close();
        cout << "插入字典成功" << endl;
        return true;
    }

public:
    Dict(const string& path = fpath) : filepath(path)
    {
        Load();
    }
    // 翻译方法
    string Translate(const string& word)
    {
        auto iter = _dict.find(word);
        if(iter == _dict.end())
        {
            return "未找到";
        }
        return iter->second;
    }
    ~Dict()
    {   }

private:
    unordered_map<string, string> _dict;
    string filepath;
};
